package repository

import (
	"context"
	"time"

	"gitee.com/thewalkers/refactoring-code/model"
	"gitee.com/thewalkers/refactoring-code/model/apperrors"
	"github.com/jmoiron/sqlx"
	"go.uber.org/zap"
)

// MysqlSaleReceiptRepository s data/repository implementation
// of service layer EmployeeRepository
type MysqlSaleReceiptRepository struct {
	DB *sqlx.DB
}

// NewTimeReceiptRepository s a factory for initializing Employee Repository
func NewSaleReceiptRepository(db *sqlx.DB) model.SaleReceiptChargeRepository {
	return &MysqlSaleReceiptRepository{
		DB: db,
	}
}

func (m *MysqlSaleReceiptRepository) Create(ctx context.Context, s *model.SaleReceipt) error {
	query := `INSERT INTO sale_receipt(commissioned_classification_id, amount) VALUES(?, ?)`

	if _, err := m.DB.Exec(query, s.CommissionedClassificationID, s.Amount); err != nil {
		zap.L().Error("repository cound not create a sale receipt with err: ", zap.Error(err))
		return apperrors.NewInternal()
	}

	return nil
}

func (m *MysqlSaleReceiptRepository) GetAmount(ctx context.Context, id int64) (float64, error) {
	saleReceipt := &model.SaleReceipt{}

	query := `SELECT * FROM sale_receipt WHERE id = ?`
	if err := m.DB.Get(saleReceipt, query, id); err != nil {
		zap.L().Error("repository could not get a sale receipt with err:", zap.Error(err))
		return saleReceipt.Amount, apperrors.NewInternal()
	}

	return saleReceipt.Amount, nil
}

func (m *MysqlSaleReceiptRepository) GetSaleDate(ctx context.Context, id int64) (time.Time, error) {
	saleReceipt := &model.SaleReceipt{}

	query := `SELECT * FROM sale_receipt WHERE id = ?`
	if err := m.DB.Get(saleReceipt, query, id); err != nil {
		zap.L().Error("repository could not get a sale receipt with err:", zap.Error(err))
		return saleReceipt.DateTime, apperrors.NewInternal()
	}

	return saleReceipt.DateTime, nil
}
